package com.wan.net.core.client;

import com.wan.net.config.HostAndPort;
import com.wan.net.core.websocket.WebsocketCodec;
import com.wan.util.Constants;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.websocketx.WebSocketClientProtocolConfig;
import io.netty.handler.codec.http.websocketx.WebSocketClientProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

import javax.annotation.Nullable;

/**
 * @author wwh
 * @date 2022/6/16 14:57
 */
public class WebsocketClient extends AbstractClient{

    private final WebSocketClientProtocolConfig webSocketClientProtocolConfig;

    public WebsocketClient(HostAndPort host) {
        this(host,null);
    }

    public WebsocketClient(HostAndPort hostAndPort, @Nullable ChannelHandler channelHandler) {
        this(hostAndPort, IDLE_TIMEOUT,channelHandler);
    }

    public WebsocketClient(HostAndPort hostAndPort, int idleTimeout) {
        this(hostAndPort, idleTimeout,null);
    }

    public WebsocketClient(HostAndPort hostAndPort, int idleTimeout, @Nullable ChannelHandler channelHandler) {
        //TODO 暂不支持Https，待添加
        this(hostAndPort, idleTimeout, channelHandler, WebSocketClientProtocolConfig.newBuilder()
                .webSocketUri("http://" + hostAndPort + "/ws")
                .build());
    }

    public WebsocketClient(HostAndPort hostAndPort, int idleTimeout, @Nullable ChannelHandler channelHandler,
                           WebSocketClientProtocolConfig webSocketClientProtocolConfig) {
        super(hostAndPort, idleTimeout, channelHandler);
        this.webSocketClientProtocolConfig = webSocketClientProtocolConfig;
    }


    @Override
    protected void channelChannelInitializer(ChannelPipeline pipeline) {
        // 编解码 http 请求
        pipeline.addLast(new HttpClientCodec(8 * Constants.BYTE_OF_KB, 16 * Constants.BYTE_OF_KB, 16 * Constants.BYTE_OF_KB));
        // 聚合解码 HttpRequest/HttpContent/LastHttpContent 到 FullHttpRequest
        // 保证接收的 Http 请求的完整性
        pipeline.addLast(new HttpObjectAggregator(16 * Constants.BYTE_OF_MB));
        // 处理其他的 WebSocketFrame
        pipeline.addLast(new WebSocketClientProtocolHandler(webSocketClientProtocolConfig));
        // 写文件内容，支持异步发送大的码流，一般用于发送文件流
        pipeline.addLast(new ChunkedWriteHandler());
        // 编解码WebSocketFrame二进制协议
        pipeline.addLast(new WebsocketCodec());
    }

    @Override
    public ClientType getClientType() {
        return ClientType.WEB_SOCKET;
    }

    @Override
    protected void onInactive() {
        open();
    }
}
